<?php

namespace IDock\Insurance\QHIC\Response;

use IDock\Http\Request;
use IDock\Http\Response;

class AllQHICResponse extends Response
{

    public function resolve(): Response
    {
        if ($this->printer and  is_string($this->printer)) {
            $this->printer = new $this->printer;
        }
        $body = $this->getBody();
        if (!json_decode($body)) {
            $this->setError('返回数据异常');
            return  $this;
        }
        $data = json_decode($body,true);

        $resultCode = $data['Head']['ErrorCode'] ?? '';
        $resultMess = $data['Head']['ErrorMessage'] ?? '';

        if($resultCode != '0000') {
            $this->setError($resultMess);
            return $this;
        }
        $this->setBody($data);

        return $this;
    }

    public function decrypt($key,Request $request)
    {
        $body = $this->getBody();
        $data = $body['Body'] ?? '';
        if(!empty($data) && is_string($data)){
            $options = OPENSSL_RAW_DATA;
            $cipher = 'AES-128-CBC';
            $iv = '0123456789ABCDEF';
            $key  = substr(openssl_digest(openssl_digest($key, 'sha1', true), 'sha1', true), 0, 16);
            $encrypted = openssl_decrypt(base64_decode($data), $cipher, $key, $options, $iv);
            if(empty($encrypted)){
                $this->setError( '解密失败');
                return  $this;
            }
            $request->decryptLogs($request->getRequestId(),$encrypted);
            $this->setBody(json_decode($encrypted,true));
        }

        return $this;
    }
}
